package com.why.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.why.pojo.Order;
import com.why.pojo.Product;
import com.why.pojo.User;
import com.why.service.OrderService;
import com.why.service.ProductService;
import com.why.service.UserAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

@RestController
public class OrderController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    //我的订单列表
    @RequestMapping(value = "userorderlist",produces = "application/json;charset=utf-8")
    public String userOrderList(HttpServletRequest request,Integer pageNum,Integer pageSize){

        User user = userData(request);
        PageInfo<Order> pageInfo = orderService.selectOrderByUserId(user.getId(),pageNum,pageSize);
        return JSON.toJSONStringWithDateFormat(pageInfo,"YYYY-MM-dd HH:mm:ss");

    }

    //所有订单列表
    @RequestMapping(value = "alluserorderlist",produces = "application/json;charset=utf-8")
    public String allUserOrderList(Integer pageNum,Integer pageSize){
        PageInfo<Order> pageInfo = orderService.selectOrderByUserId(null,pageNum,pageSize);
        return JSON.toJSONStringWithDateFormat(pageInfo,"YYYY-MM-dd HH:mm:ss");

    }

    //取消订单
    @RequestMapping(value = "cancelorder",produces = "application/json;charset=utf-8")
    public String cancelOrder(Integer orderId){
        boolean result = orderService.cancelOrderById(orderId);
        return JSON.toJSONString(result);

    }

    //取消订单
    @RequestMapping(value = "deleteorder",produces = "application/json;charset=utf-8")
    public String deleteOrder(Integer orderId){
        boolean result = orderService.deleteOrderById(orderId);
        return JSON.toJSONString(result);
    }

    //获取用户信息，由于本类调用
    public User userData(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        //redis
        User user = null;
        for(Cookie cookie : cookies){
            if (cookie.getName().equals("cookieUser")){
                HashMap<String,Object> map = (HashMap<String, Object>) redisTemplate.opsForValue().get(cookie.getValue());
                user = (User) map.get("user");
            }
        }
        return user;
    }
}
